let tableIns;
let tree;
layui.use(['table', 'layer', 'laydate', 'tree', 'util'], function () {
    let table = layui.table;
    tree = layui.tree;
    let laydate = layui.laydate;
    let form = layui.form;
    let height = document.documentElement.clientHeight - 60;

    tableIns = table.render({
        elem: '#invoiceTable'
        , url: '/platform/profit/queryByProfit'
        , method: 'GET'
        , where: {
             sellerName: ""
            , startDate: ""
            , endDate: ""
            }
        //请求前参数处理
        , request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'rows' //每页数据量的参数名，默认：limit
        }
        , response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
            , countName: 'records' //规定数据总数的字段名称，默认：count
            , dataName: 'rows' //规定数据列表的字段名称，默认：data
        }
        //响应后数据处理
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            var sum=0;
            var num=0;
            var total = 0;
            for(i=0;i<data.rows.length;i++){
            	if(data.rows[i].investTotal >0){
            		sum=sum+data.rows[i].investTotal;            		
            	}
            	if(data.rows[i].sendAmount >0){
            		num=num+data.rows[i].sendAmount;            		
            	}
            	//计算个税
            	var geshui = 0;
            	if(data.rows[i].sendAmount > 0){
            		geshui = data.rows[i].sendAmount-data.rows[i].sendAmount/1.01;
            	}
            	//计算发放金额的6.72%
            	var fafang = 0;
            	if(data.rows[i].sendAmount > 0){
            		fafang = data.rows[i].sendAmount*0.0672;
            	}
            	var zonghe=0;
            	if(data.rows[i].serverAmount >0){
            		zonghe = data.rows[i].serverAmount*data.rows[i].serverAmountPoint-geshui-fafang-data.rows[i].givemoney;
            	}
            	total=total+zonghe;
            }
            $("#sum_money1").html("充值总金额："+formatMoney(sum));
            $("#sum_money2").html("发放总金额："+formatMoney(num));
            $("#sum_money3").html("平台总利润："+formatMoney(total));
            
            // console.log("data=="+data);
            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "records": data.records, //解析数据长度
                "rows": data.rows //解析数据列表
            };
        }
        , toolbar: true
        , title: '企业开票'
        , cols: [[
            {field: 'sellerName', title: '商户名称'},
            {field: 'investTotal', title: '充值金额（元）'},
            {field: 'serverAmount', title: '服务费扣除（元）'},
            {field: 'sendAmount', title: '累计发放（元）'},
            {field: 'sendAmount',title: '税额（个税）', templet: function(d){
            	var sum = 0;
            	if(d.sendAmount > 0){
            		sum = d.sendAmount-d.sendAmount/1.01;
            	}
            return sum.toFixed(2); ;
            }},
            {field: 'givemoney', title: '代理商佣金'},
            {field: 'givemoney', title: '平台净收益', templet: function(d){
            	//计算个税
            	var geshui = 0;
            	if(d.sendAmount > 0){
            		geshui = d.sendAmount-d.sendAmount/1.01;
            	}
            	//计算发放金额的6.72%
            	var fafang = 0;
            	if(d.sendAmount > 0){
            		fafang = d.sendAmount*0.0672;
            	}
            	var zonghe=0;
            	if(d.serverAmount >0){
            		zonghe = d.serverAmount*d.serverAmountPoint-geshui-fafang-d.givemoney;
            	}
            return zonghe.toFixed(2); ;
            }},
        ]]
        , defaultToolbar: ['', '', '']
        //, page: true
        , height: height
        , cellMinWidth: 80
    });
    
    
    form.on('submit(menu-query)', function (data) {
    	
      	 // 搜索条件
          var sellerName=data.field.sellerName;
          var startDate=data.field.startDate;
          var endDate=data.field.endDate;
          if(startDate != '' && endDate =='' || startDate == '' && endDate !=''){
       	   alert('起始日期和结束日期都需要填！');
       	   return false;
          }
          	// var tel=$("#tel").val();
              table.reload('invoiceTable', {
                  url:'/platform/profit/queryByProfit'
                  , where: {
                      'sellerName':sellerName,
                      'startDate':startDate,
                      'endDate':endDate,
                  }
                  , page: {
                      curr: 1
                  }
              });
              return false;
          
     });
       
       
       //日期选择器
       startDateIns = laydate.render({
           elem: '#queryByStartDate',
           format: "yyyy-MM",
           type: 'month',
           trigger: 'click'
       });

       
       //日期选择器
       endDateIns = laydate.render({
           elem: '#queryByEndDate',
           format: "yyyy-MM",
           type: 'month',
           trigger: 'click'
       });



});


function formatMoney(str) {
    if (!str) str = '0.00';
    let ret = Math.round(parseFloat(str) * 100) / 100;
    let decimal = ret.toString().split('.');
    if (decimal.length === 1) {
        return ret.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
            + '.00';
    };
    if (decimal.length > 1) {
        decimal[0] = decimal[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        if (decimal[1].length < 2) {
            decimal[1] += '0';
            return decimal.join(".");
        }
        return decimal.join(".");
    };
    return ret;
}